import React, { useEffect, useRef, useState } from "react";
import { Form, Input, Button, Space, message } from 'antd';
import '../css/Login.css'
import axios from 'axios'
import { useNavigate } from "react-router-dom";
import cookie from 'react-cookies'

function Login() {

  let navigate = useNavigate();
  //获取dom元素
  const form_box = useRef<any>();
  const login_box = useRef<any>();
  const register_box = useRef<any>();

  //控制登录注册的显示隐藏
  const [flag, setFlag] = useState<string>('true');
  //登录的用户信息
  const [userinfo, setUserinfo] = useState<{ username: string, password: string }>({ username: '', password: '' });

  const key = 'updatable';


  //注册成功的回调
  const register = async (values: any) => {
    console.log('Success:', values);
    const res = await axios.post('http://localhost:7001/adminregister', values);
    console.log('111', res);
    // 成功信息提示
    message.loading({ content: 'Loading...', key });
    setTimeout(() => {
      message.success({ content: 'Registered successfullyv!', key, duration: 1 });
    }, 500);

    gologin();
  };

  //注册失败的回调
  const registerFailed = (errorInfo: any) => {
    // console.log('Failed:', errorInfo);
    message.error('registration failed');
  };

  //登录成功的回调
  const login = async (values: any) => {
    // console.log('Success:', values);
    const res = await axios.get('http://localhost:7001/adminlogin', values);
    console.log('111', res);
    // 保存登录用户信息
    setUserinfo(values);
    if (res.status === 200) {//登陆成功
      // 成功信息提示
      message.loading({ content: 'Loading...', key });
      setTimeout(() => {
        message.success({ content: 'Login successfully!', key, duration: 1 });
      }, 500);

      let inFifteenMinutes = new Date(new Date().getTime() + 24 * 3600 * 1000);//一天
      cookie.save('userinfo', values, { expires: inFifteenMinutes });
      // document.cookie = "no=" + res.status;
      //跳转主页面
      navigate({ pathname: '/home' });
    }

  };

  //登录失败的回调
  const loginFailed = (errorInfo: any) => {
    // console.log('Failed:', errorInfo);
    message.error('Login failed');
  };

  // 注册登录的平移切换
  function gologin() {
    form_box.current.style.transform = 'translateX(0%)';
    setFlag("true")
  }
  function goregister() {
    form_box.current.style.transform = 'translateX(80%)';
    setFlag("none")
  }


  return (
    <div id="bodybox">
      <div className="container">
        <div className="form-box" ref={form_box}>
          <Form
            className="register-box "
            style={{ display: (flag === "true" ? "none" : "block"), transition: "0.5s" }}
            ref={register_box}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ remember: true }}//表单默认值
            onFinish={register}//提交表单且数据验证成功后回调事件
            onFinishFailed={registerFailed}//提交表单且数据验证失败后回调事件
            autoComplete="off"
          >
            <Form.Item
              label="Username"
              name="username"
              rules={[{ required: true, message: 'Please input your username!' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="password"
              label="Password"
              rules={[
                {
                  required: true,
                  message: 'Please input your password!',
                },
              ]}
              hasFeedback
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="confirm"
              label="Confirm Password"
              dependencies={['password']}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: 'Please confirm your password!',
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('The two passwords that you entered do not match!'));
                  },
                }),
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  Register
                </Button>
                <Button type="primary" htmlType="reset">
                  Reset
                </Button>
              </Space>
            </Form.Item>
          </Form>

          <Form
            className="login-box"
            style={{ display: (flag === "true" ? "block" : "none"), transition: "0.5s" }}
            ref={login_box}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            // initialValues={{ remember: true }}//表单默认值
            onFinish={login}//提交表单且数据验证成功后回调事件
            onFinishFailed={loginFailed}//提交表单且数据验证失败后回调事件
            autoComplete="off"
          >
            <Form.Item
              label="Username"
              name="username"
              initialValue={userinfo.username}
              rules={[{ required: true, message: 'Please input your username!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="Password"
              name="password"
              initialValue={userinfo.password}
              rules={[{ required: true, message: 'Please input your password!' }]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  Log in
                </Button>
                <Button type="primary" htmlType="reset">
                  Reset
                </Button>
              </Space>
            </Form.Item>

          </Form>

        </div>
        <div className="con-box left">
          <h2>Welcome to <span>VFP</span></h2>
          <p>let's <span>start</span>!</p>
          <p>Already have an account</p>
          <button id="login" onClick={gologin}>login now!</button>
        </div>
        <div className="con-box right">
          <h2>Welcome to <span>VFP</span></h2>
          <p>let's <span>start</span>!</p>
          <p>No account？</p>
          <button id="register" onClick={goregister}>register now!</button>
        </div>
      </div>
    </div>
  );
}

export default Login;